package com.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.mapper.UserMapper;
import com.project.model.User;
import com.project.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    @Transactional
    public User createUser(User user) {
        try {
            // 加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));

            // 设置默认值
            user.setStatus(1);  // 普通用户直接启用
            if ("DOCTOR".equals(user.getRole())) {
                user.setStatus(0);  // 医生需要审核
            }

            // 保存用户
            save(user);
            return user;
        } catch (Exception e) {
            log.error("创建用户失败", e);
        }
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        return lambdaQuery()
            .eq(User::getUsername, username)
            .one();
    }

    @Override
    public boolean checkUsernameExists(String username) {
        return lambdaQuery()
            .eq(User::getUsername, username)
            .exists();
    }
}
